package geyue.wechat.service;
import geyue.wechat.model.WechatMeta;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.util.EntityUtils;
import com.alibaba.fastjson.JSONObject;
import com.blade.kit.StringKit;


public class WeChatSendImg {
	public String upload(String filePath,WechatMeta wechatMeta,String toUserName,String type) {
		String domain="wx2";
		String uIn = wechatMeta.getWxuin();
    	String sId = wechatMeta.getWxsid();
    	String sKey = wechatMeta.getSkey();
    	String deviceid = wechatMeta.getDeviceId();
    	String webwxDataTicket = "";
		String[] split = wechatMeta.getCookie().split(";");
		for (String str : split) {
			if(str.indexOf("webwx_data_ticket") != -1){
				webwxDataTicket = (str.split("="))[1];
			}
		}
		String passTicket =  wechatMeta.getPass_ticket();
    	String fromUserName = wechatMeta.getUser().getString("UserName");
    	
    	String response = null;
    	InputStream inputStream = null;
    	InputStreamReader inputStreamReader = null;
    	BufferedReader bufferedReader = null;
    	HttpsURLConnection conn = null;
    	try {
    		File file = new File(filePath);
    		if (!file.exists() || !file.isFile()) {
    			throw new IOException("文件不存在");
    		}
    		
    		//请求头参数
    		String boundary = "---------------------------16968206128770"; //区分每个参数之间
    		String freFix = "--";
    		String newLine = "\r\n";
    		    		
    		URL urlObj = new URL("https://file."+domain+".qq.com/cgi-bin/mmwebwx-bin/webwxuploadmedia?f=json");
    		conn = (HttpsURLConnection) urlObj.openConnection();
    		conn.setRequestMethod(type);
    		conn.setDoOutput(true);
    		conn.setDoInput(true);
    		conn.setConnectTimeout(5000);  
    		conn.setUseCaches(false);
    		conn.setRequestMethod("POST");
    		conn.setRequestProperty("Host", "file."+domain+".qq.com");
    		conn.setRequestProperty("User-Agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:49.0) Gecko/20100101 Firefox/49.0");
    		conn.setRequestProperty("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8");
    		conn.setRequestProperty("Accept-Language", "zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3");
    		conn.setRequestProperty("Accept-Encoding", "gzip, deflate, br");
    		conn.setRequestProperty("Referer", "https://."+domain+".qq.com/?&lang=zh_CN");
    		conn.setRequestProperty("Content-Length", Long.toString(file.length()));
    		conn.setRequestProperty("Content-Type", "multipart/form-data; boundary="+boundary);
    		conn.setRequestProperty("origin", "https://."+domain+"..qq.com/");
    		conn.setRequestProperty("Connection", "Keep-Alive");
    		conn.setRequestProperty("Cookie", wechatMeta.getCookie());
    		
    		// 请求主体
    		StringBuffer sb = new StringBuffer();
    		
    		sb.append(freFix+boundary).append(newLine); //这里注意多了个freFix，来区分去请求头中的参数
    		sb.append("Content-Disposition: form-data; name=\"id\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append("WU_FILE_1").append(newLine);
    		sb.append(freFix+boundary).append(newLine); 
    		sb.append("Content-Disposition: form-data; name=\"name\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append(file.getName()).append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"type\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append("image/jpeg").append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"lastModifiedDate\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append("Tue Feb 14 2017 22:07:03 GMT+0800").append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"size\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append(file.length()).append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"mediatype\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append("pic").append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"uploadmediarequest\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append("{\"UploadType\":2,\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\""+sKey+"\",\"DeviceID\":\""+deviceid+StringKit.getRandomNumber(5)+"\"},\"ClientMediaId\":"+System.currentTimeMillis()+",\"TotalLen\":"+file.length()+",\"StartPos\":0,\"DataLen\":"+file.length()+",\"MediaType\":4,\"FromUserName\":\""+fromUserName+"\",\"ToUserName\":\""+toUserName+"\",\"FileMd5\":\"7a392dfff5a45cc29d494434a1fbaf15\"}").append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"webwx_data_ticket\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append(webwxDataTicket).append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"pass_ticket\"").append(newLine);
    		sb.append(newLine);
    		
    		sb.append(passTicket).append(newLine);
    		sb.append(freFix+boundary).append(newLine);
    		sb.append("Content-Disposition: form-data; name=\"filename\"; filename=\""+file.getName()+"\"").append(newLine);
    		sb.append("Content-Type: application/octet-stream");
    		sb.append(newLine);
    		sb.append(newLine);
    		
    		// System.out.println(sb.toString());
    		//FileOutputStream writer = new FileOutputStream(new File("e:\\img\\Resulsssst.txt"));  
    		OutputStream outputStream = new DataOutputStream(conn.getOutputStream());
    		outputStream.write(sb.toString().getBytes("utf-8"));//写入请求参数
    
    		DataInputStream dis = new DataInputStream(new FileInputStream(file));  
    		int bytes = 0;  
    		byte[] bufferOut = new byte[1024];  
    		while ((bytes = dis.read(bufferOut)) != -1) {  
    			outputStream.write(bufferOut,0,bytes);//写入图片
    		}
    		outputStream.write(newLine.getBytes());
    		outputStream.write((freFix+boundary+freFix+newLine).getBytes("utf-8"));//标识请求数据写入结束
    		dis.close();  
    		outputStream.close();
    		//读取响应信息
    		inputStream = conn.getInputStream();
    		inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
    		bufferedReader = new BufferedReader(inputStreamReader);
    		String str = null;
    		StringBuffer buffer = new StringBuffer();
    		while ((str = bufferedReader.readLine()) != null) {
    			buffer.append(str);
    		}
    		response = buffer.toString();
    		System.out.println("response++++++++"+response);
    	} catch (Exception e) {
    		e.printStackTrace();
    	}finally{
    		if(conn!=null){
    			conn.disconnect();
    		}
    		try {
    			bufferedReader.close();
    			inputStreamReader.close();
    			inputStream.close();
    		} catch (IOException execption) {
    			
    		}
    	}
    	return response;
    }

    public String send(String picPath,WechatMeta wechatMeta,String toUserName) throws Exception{
    	
    	String filePath = "D:/1.jpg";
        String fileName = "1.jpg";
        String uIn = wechatMeta.getWxuin();
        String sId = wechatMeta.getWxsid();
        String sKey = wechatMeta.getSkey();
        String deviceid = wechatMeta.getDeviceId();
        String cookie = wechatMeta.getCookie();
        String fromUserName = wechatMeta.getUser().getString("UserName");
        String result = upload(filePath,wechatMeta,toUserName,"POST"); 
      
        JSONObject json = JSONObject.parseObject(result);
        Long currentTimeMillis = System.currentTimeMillis();
        //String jsonParamsByFile = "{\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\""+sKey+"\",\"DeviceID\":\""+deviceid+"\"},\"Msg\":{\"Type\":6,\"Content\":\"<appmsg appid=\'wxeb7ec651dd0aefa9\' sdkver=\'\'><title>"+fileName+"</title><des></des><action></action><type>6</type><content></content><url></url><lowurl></lowurl><appattach><totallen>9879</totallen><attachid>"+json.get("MediaId").toString()+"</attachid><fileext>jpg</fileext></appattach><extinfo></extinfo></appmsg>\",\"FromUserName\":\""+fromUserName+"\",\"ToUserName\":\""+toUserName+"\",\"LocalID\":\""+currentTimeMillis+"\",\"ClientMsgId\":\""+currentTimeMillis+"\"}}";
        String jsonParamsByFile = "{\"BaseRequest\":{\"Uin\":"+uIn+",\"Sid\":\""+sId+"\",\"Skey\":\""+sKey+"\",\"DeviceID\":\""+deviceid+"\"},\"Msg\":{\"Type\":3,"+"\"MediaId\":\""+json.get("MediaId").toString()+"\",\"FromUserName\":\""+fromUserName+"\",\"ToUserName\":\""+toUserName+"\",\"LocalID\":\""+currentTimeMillis+"\",\"ClientMsgId\":\""+currentTimeMillis+"\"},\"Scene\":0}";
        System.out.println("jsonParamsByFile********"+jsonParamsByFile);     
        String url = "https://wx2.qq.com/cgi-bin/mmwebwx-bin/webwxsendmsgimg?fun=async&f=json&lang=zh_CN";  
                      
        HttpClient client = new DefaultHttpClient();
        HttpPost post = new HttpPost(url);
        post.addHeader(new BasicHeader("cookie", cookie));//发送文件必须设置,cookie

        try {
            StringEntity s = new StringEntity(jsonParamsByFile);
            post.setEntity(s);
            HttpResponse res = client.execute(post);
            if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK){
                HttpEntity entity = res.getEntity();
                System.out.println(EntityUtils.toString(entity, "utf-8"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }  
        return json.get("MediaId").toString();
    }
       
}
